import { Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { LocalStorage } from '@core/local.storage';
import { ReuseTabService } from '@delon/abc';
import { TctjDayService } from './tctj_day.service';
import { ExportFileService } from '@core/exportFile';
import { environment } from '../../../../../environments/environment';

@Component({
  selector: 'app-tctj-day',
  templateUrl: './tctj_day.component.html',
  styleUrls: ['./tctj_day.component.less', '../tctj.less']
})
export class TctjDayComponent implements OnInit {

  userInfo = JSON.parse(this.ls.get('loginInfo'));
  queryParam: any = {};
  // cjList: any[] = [];
  // gqList: any[] = [];
  // czList: any[] = [];
  tableData: any[] = [];
  tableDataSum: any = {};
  isRange: boolean;
  tableInfo: any = {};
  titleDate = new Date();
  // expandGrid: any[] = [];

  lockHeadScroll = { x: '1600px', y: window.innerHeight - 350 + 'px' };
  detail: any = {
    visible: false,
    selectedValue: 1,
    pageIndex: 0,
    pageTotal: 0,
    footer: [{
      _this: this,
      label: '关闭', // 按钮文本
      onClick() {
        this._this.detailCancel();
      }
    }]
  };


  constructor(
    private datePipe: DatePipe,
    public ls: LocalStorage,
    private tctjDayService: TctjDayService,
    private exportFile: ExportFileService,
    private reuseTabService: ReuseTabService
  ) { }

  ngOnInit(): void {
    this.reuseTabService.title = '天窗兑现率日统计';
    this.setQueryDate('day');
    this.query();
  }
  setQueryDate(type) {
    // let start, end;
    switch (type) {
      case 'day':
        const today = new Date();
        // start = today;
        // end = today;
        this.queryParam._workdateStart = today;
        this.queryParam._workdateEnd = today;
        break;
      case 'week':
        const beginDate_w = new Date();
        const weekday = beginDate_w.getDay();
        beginDate_w.setDate(beginDate_w.getDate() - weekday + 1);
        const endDate_w = new Date();
        endDate_w.setDate(beginDate_w.getDate() + 6);
        this.queryParam._workdateStart = beginDate_w;
        this.queryParam._workdateEnd = endDate_w;
        break;
      case 'month':
        const beginDate_m = new Date();
        beginDate_m.setDate(1);
        const endDate_m = new Date();
        endDate_m.setMonth(endDate_m.getMonth() + 1);
        endDate_m.setDate(0);
        this.queryParam._workdateStart = beginDate_m;
        this.queryParam._workdateEnd = endDate_m;
        break;
      case 'year':
        const beginDate_y = new Date();
        beginDate_y.setDate(1);
        beginDate_y.setMonth(0);
        const endDate_y = new Date();
        endDate_y.setMonth(11);
        endDate_y.setDate(31);
        this.queryParam._workdateStart = beginDate_y;
        this.queryParam._workdateEnd = endDate_y;
        break;
    }
  }

  /**
     * 删除私立字段
     * @param param
     */
  removePrivateFields(param) {
    Object.keys(param).forEach(key => {
      if (key.indexOf('_') == 0) {
        delete param[key];
      }
    });
  }

  formatDate(param) {
    if (param._workdateStart) {
      param.workdateStart = this.datePipe.transform(param._workdateStart, 'yyyy-MM-dd');
    }
    if (param._workdateEnd) {
      param.workdateEnd = this.datePipe.transform(param._workdateEnd, 'yyyy-MM-dd');
    }
  }

  isDateRange(queryParam) {
    let isRange = true;
    if (queryParam.workdateStart && queryParam.workdateEnd) {
      isRange = queryParam.workdateStart != queryParam.workdateEnd;
    }
    this.isRange = isRange;
  }

  getTableSum(tableData) {
    tableData.forEach(row => {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          const el = row[key];
          if (!el) {
            row[key] = '0';
          }
        }
      }
    });
    return tableData[0] || {};
  }

  /**
   * 未兑现
   * @param tableInfo
   */
  getWdx(tableInfo) {
    const wdx = tableInfo.nocashinfos;
    let str = '';
    wdx.forEach((el, index) => {
      const text = el.statoin;
      // const v = el.nums;
      str += `${index + 1}.${text}:<br>`;
    });
    return str;
  }

  query() {
    const param = {};
    Object.assign(param, this.queryParam);
    this.formatDate(param);
    this.removePrivateFields(param);
    this.isDateRange(param);
    this.tctjDayService.query(param).subscribe(res => {
      const data = res.data;
      this.tableData = data[0].grid;
      this.tableData[0]._leftSpace = 0;
      this.tableDataSum = this.getTableSum(data[0].grid);

      this.tableInfo = data[0].info;
      this.tableInfo.wdxStr = this.getWdx(this.tableInfo);
    });
  }

  collapse(id, data) {
    const delIds = [];
    data.forEach(row => {
      if (row._pId == id) {
        delIds.push(row.unit);
      }
    });
    data = data.filter(row => row._pId != id);
    delIds.forEach(_id => {
      data = this.collapse(_id, data);
    });
    return data;
  }

  expand(id) {
    const copy = JSON.parse(JSON.stringify(this.tableData));
    const index = copy.findIndex(row => row.unit == id);
    if (copy[index]._expand) {
      copy[index]._expand = false;
      const collapsRes = this.collapse(id, copy);
      this.tableData = collapsRes || [];
      return;
    }
    const param: any = {};
    Object.assign(param, this.queryParam);
    this.formatDate(param);
    this.removePrivateFields(param);
    // if (unitKey) {
    //   param[unitKey] = id;
    // }
    param.unit = id;
    this.tctjDayService.expand(param).subscribe(res => { 
      if (res && res.data && res.data.length && res.data[0].grid) {
        const grid = res.data[0].grid;
        grid.forEach(row => {
          row._pId = id;
          row._leftSpace = +copy[index]._leftSpace + 1;
        });

        copy[index]._expand = true;
        if (index != -1) {
          copy.splice((index + 1), 0, grid);
          this.tableData = copy.flat();
        }
      }
    });
  }

  getDetail(id, type) {
    const param: any = {
      unit: id,
      detailType: type
    };
    Object.assign(param, this.queryParam);
    this.formatDate(param);
    this.removePrivateFields(param);
    this.tctjDayService.detail(param).subscribe(res => { 
      this.detail.tableData = res.data;
      this.detail.tableType = type;
    });
    this.detail.visible = true;
  }

  detailCancel() {
    this.detail.visible = false;
  }

  export() {
    const param: any = {};
    Object.assign(param, this.queryParam);
    this.formatDate(param);
    this.exportFile.postDown(environment.project + '/skywinStat/dayStatExport', { workdateStart: param.workdateStart, workdateEnd: param.workdateEnd }, '天窗统计' + param.workdateStart + '-' + param.workdateEnd + '.xls');
  }
}
